package oidc

import (
	"project-info/src/handle/oidc/handler"
	"project-info/src/lib"
	"project-info/src/model"
	"project-info/src/router/req"
	"project-info/src/router/variable"
	"time"

	"github.com/gin-gonic/gin"
)

// init 自动注册OIDC路由
func init() {
	variable.InitRouteFunc = append(variable.InitRouteFunc, registerOIDCRoutes)
}

// registerOIDCRoutes 注册OIDC相关路由
func registerOIDCRoutes(e *gin.Engine) {
	// OIDC协议端点组
	oidcGroup := e.Group("/oidc")
	reqs := []*req.Conf{
		// OpenID Connect Discovery端点
		// GET /.well-known/openid_configuration
		req.NewGet("/.well-known/openid_configuration", handler.WellKnownConfiguration),

		// JWKS端点
		// GET /.well-known/jwks.json
		req.NewGet("/.well-known/jwks.json", handler.JWKS),

		// 授权端点
		// GET/POST /auth
		req.NewGet("/auth", handler.Authorization),
		req.NewPost("/auth", handler.Authorization),

		// 令牌端点
		// POST /token
		req.NewPost("/token", handler.Token),

		// 用户信息端点
		// GET/POST /userinfo
		req.NewGet("/userinfo", handler.UserInfo),
		req.NewPost("/userinfo", handler.UserInfo),

		// 令牌撤销端点
		// POST /revoke
		req.NewPost("/revoke", handler.TokenRevocation),

		// 令牌内省端点
		// POST /introspect
		req.NewPost("/introspect", handler.TokenIntrospection),

		// 登出端点
		// GET/POST /logout
		req.NewGet("/logout", handler.Logout),
		req.NewPost("/logout", handler.Logout),
	}
	req.BatchSetUpRouter(oidcGroup, reqs)

	// 管理API端点组（用于客户端管理、令牌管理等）
	adminGroup := e.Group("/oidc/admin")
	reqs = []*req.Conf{
		// 客户端管理端点
		req.NewGet("/clients", handler.ListClients),                               // 获取客户端列表
		req.NewGet("/client", handler.GetClient),                                  // 获取单个客户端 ?id=client_id
		req.NewPost("/clients", handler.CreateClient),                             // 创建客户端
		req.NewPut("/clients", handler.UpdateClient),                              // 更新客户端 ?id=client_id
		req.NewDelete("/clients", handler.DeleteClient),                           // 删除客户端 ?id=client_id
		req.NewPost("/clients/regenerate-secret", handler.RegenerateClientSecret), // 重新生成客户端密钥 ?id=client_id
		req.NewGet("/clients/stats", handler.GetClientStats),                      // 获取客户端统计信息 ?id=client_id

		// 令牌管理端点
		req.NewGet("/tokens", handler.ListTokens),                      // 获取令牌列表
		req.NewGet("/token", handler.GetToken),                         // 获取单个令牌 ?id=token_id
		req.NewPost("/token/revoke", handler.RevokeToken),              // 撤销令牌 ?id=token_id
		req.NewPost("/tokens/batch-revoke", handler.BatchRevokeTokens), // 批量撤销令牌

		// 会话管理端点
		req.NewGet("/sessions", handler.ListSessions),                // 获取会话列表
		req.NewDelete("/session", handler.RevokeSession),             // 撤销会话 ?id=session_id
		req.NewPost("/sessions/batch-end", handler.BatchEndSessions), // 批量结束会话

		// 作用域管理端点
		req.NewPost("/scope", handler.CreateScope),            // 创建作用域
		req.NewGet("/scopes", handler.ListScopes),             // 获取作用域列表
		req.NewGet("/scope/options", handler.GetScopeOptions), // 获取作用域选项
		req.NewGet("/scope", handler.GetScope),                // 获取单个作用域 ?id=scope_id
		req.NewPut("/scope", handler.UpdateScope),             // 更新作用域 ?id=scope_id
		req.NewDelete("/scope", handler.DeleteScope),          // 删除作用域 ?id=scope_id

		// 审计日志端点
		req.NewGet("/audit/logs", handler.GetAuditLogs), // 获取审计日志

		// 系统管理端点
		req.NewGet("/statistics", handler.GetSystemStats),     // 获取系统统计信息
		req.NewPost("/cleanup", handler.CleanupExpiredTokens), // 清理过期令牌
	}
	req.BatchSetUpRouter(adminGroup, reqs)

	// 测试页面
	req.NewGet("/test", handler.TestPage)

	// 健康检查端点
	req.NewGet("/health", func(c *lib.GinContext) error {
		return c.JSON(200, map[string]interface{}{
			"status":    "ok",
			"service":   "OIDC Provider",
			"version":   "1.0.0",
			"timestamp": "2024-01-01T00:00:00Z",
		})
	})

	// 状态端点
	req.NewGet("/status", handler.OIDCStatus)

	// 调试端点（仅开发环境使用）
	req.NewGet("/debug/tokens", func(c *lib.GinContext) error {
		// 返回当前存储的令牌信息（去除敏感信息）
		db := model.DB()
		var accessTokenCount, refreshTokenCount, authCodeCount, sessionCount, clientCount int64

		// 统计各种数据的数量
		db.Model(&model.OIDCAccessToken{}).Where("deleted = 0").Count(&accessTokenCount)
		db.Model(&model.OIDCRefreshToken{}).Where("deleted = 0").Count(&refreshTokenCount)
		db.Model(&model.OIDCAuthorizationCode{}).Where("deleted = 0 AND expires_at > ?", time.Now()).Count(&authCodeCount)
		db.Model(&model.OIDCUserSession{}).Where("deleted = 0").Count(&sessionCount)
		db.Model(&model.OIDCClient{}).Where("deleted = 0").Count(&clientCount)

		debugInfo := map[string]interface{}{
			"access_tokens_count":  int(accessTokenCount),
			"refresh_tokens_count": int(refreshTokenCount),
			"auth_codes_count":     int(authCodeCount),
			"sessions_count":       int(sessionCount),
			"clients_count":        int(clientCount),
		}
		return c.JSON(200, debugInfo)
	})

	// 清理端点（仅开发环境使用）
	req.NewPost("/debug/cleanup", func(c *lib.GinContext) error {
		// 清理所有数据（软删除）
		db := model.DB()
		now := time.Now()

		// 软删除所有数据
		db.Model(&model.OIDCAccessToken{}).Where("deleted = 0").Updates(map[string]interface{}{"deleted": 1, "update_time": &now})
		db.Model(&model.OIDCRefreshToken{}).Where("deleted = 0").Updates(map[string]interface{}{"deleted": 1, "update_time": &now})
		db.Model(&model.OIDCAuthorizationCode{}).Where("deleted = 0").Updates(map[string]interface{}{"deleted": 1, "update_time": &now})
		db.Model(&model.OIDCUserSession{}).Where("deleted = 0").Updates(map[string]interface{}{"deleted": 1, "update_time": &now})
		// 注意：通常不会清理客户端数据，这里注释掉
		// db.Model(&model.OIDCClient{}).Where("deleted = 0").Updates(map[string]interface{}{"deleted": 1, "update_time": &now})

		return c.JSON(200, map[string]interface{}{
			"message": "All data cleaned up (soft delete)",
		})
	})
}
